<template>
  <a-card :bordered="false">
    <!-- 查询区域 -->
    <div class="table-page-search-wrapper">
      <a-form layout="inline" @keyup.enter.native="searchQuery">
        <a-row :gutter="24">
          <a-col :md="6" :sm="12">
            <a-form-item label="sku编码">
              <a-input placeholder="请输入sku编码" v-model="queryParam.skuCode" :maxLength="20"></a-input>
            </a-form-item>
          </a-col>
          <a-col :md="6" :sm="12">
            <a-form-item label="产品名称">
              <a-input-group compact style="width: 100%; display: flex">
                <a-select
                  v-model="queryParam.nameType"
                  style="width: 70px; flex-shrink: 0"
                  default-value="cn"
                  @change="updateName"
                >
                  <a-select-option value="cn"> 中文 </a-select-option>
                  <a-select-option value="en"> 英文 </a-select-option>
                </a-select>
                <a-input placeholder="请输入产品名称" v-model="queryParam.name" @input="updateName" :maxLength="255" />
              </a-input-group>
            </a-form-item>
          </a-col>
          <a-col :md="6" :sm="12">
            <a-form-item label="产品颜色">
              <a-input placeholder="请输入产品颜色" v-model="queryParam.color" :maxLength="50"></a-input>
            </a-form-item>
          </a-col>
          <a-col :md="6" :sm="12">
            <a-form-item label="产品尺寸">
              <a-input placeholder="请输入产品尺寸" v-model="queryParam.size" :maxLength="50"></a-input>
            </a-form-item>
          </a-col>
          <a-col :md="6" :sm="12">
            <a-form-item label="销售状态">
              <j-search-select-tag-new
                placeholder="请选择销售状态"
                v-model="queryParam.sellStatus"
                dictCode="archive_sell_status"
              />
            </a-form-item>
          </a-col>
          <a-col :md="6" :sm="12">
            <a-form-item label="供应商匹配状态">
              <j-search-select-tag-new
                placeholder="请选择供应商匹配状态"
                v-model="queryParam.supplyMatch"
                :dictOptions="supplyMatchOptions"
              />
            </a-form-item>
          </a-col>
          <template v-if="toggleSearchStatus">
            <a-col :md="6" :sm="12">
              <a-form-item label="供应商">
                <j-url-select-search
                  placeholder="请输入供应商名称"
                  v-model="queryParam.supplyId"
                  url="/hzkj-product/product/productLibrary/supplier/list?pageNo=1&pageSize=10"
                  :optionDiy="optionDiy"
                />
              </a-form-item>
            </a-col>
            <a-col :md="6" :sm="12">
              <a-form-item label="成本中心">
                <j-url-select
                  placeholder="请选择成本中心"
                  v-model="queryParam.deptCode"
                  url="/sys/costCenter/queryAllByUserId"
                />
              </a-form-item>
            </a-col>
            <a-col :md="6" :sm="12">
              <a-form-item label="产品类目">
                <product-category-tree-select
                  v-model="queryParam.category"
                  :multiple="true"
                  placeholder="请选择产品类目"
                />
              </a-form-item>
            </a-col>
            <a-col :md="6" :sm="12">
              <a-form-item label="组合状态">
                <j-search-select-tag-new
                  placeholder="请选择组合状态"
                  v-model="queryParam.constituteStatus"
                  dictCode="archive_constitute_status"
                />
              </a-form-item>
            </a-col>
            <a-col :md="6" :sm="12">
              <a-form-item label="质检类型">
                <j-search-select-tag-new
                  placeholder="请选择质检类型"
                  v-model="queryParam.qualityType"
                  dictCode="qc_requirement"
                />
              </a-form-item>
            </a-col>
            <a-col :md="6" :sm="12">
              <a-form-item label="采购人">
                <j-url-select
                  v-model="queryParam.buyer"
                  placeholder="请选择采购人"
                  optionLabel="username"
                  :multiple="true"
                  url="/sys/user/getAllUserByOrg"
                />
              </a-form-item>
            </a-col>
            <a-col :md="6" :sm="12">
              <a-form-item label="以图搜图" style="height: 100px">
                <j-upload-oss v-model="queryParam.imgUrl" fileType="image" :number="1" />
              </a-form-item>
            </a-col>
          </template>
          <a-col :md="6" :sm="12">
            <span style="float: left; overflow: hidden" class="table-page-search-submitButtons">
              <a-button type="primary" @click="searchQuery" icon="search">查询</a-button>
              <a-button type="primary" @click="searchReset" icon="reload" style="margin-left: 8px">重置</a-button>
              <a @click="handleToggleSearch" style="margin-left: 8px">
                {{ toggleSearchStatus ? '收起' : '展开' }}
                <a-icon :type="toggleSearchStatus ? 'up' : 'down'" />
              </a>
            </span>
          </a-col>
        </a-row>
      </a-form>
    </div>
    <!-- 查询区域-END -->

    <!-- 操作按钮区域 -->
    <div class="table-operator">
      <a-button
        v-has="'ArchiveInfoBasicList:add'"
        @click="
          editId = ''
          showEditModal = true
        "
        type="primary"
        icon="plus"
        >创建产品</a-button
      >
      <a-dropdown>
        <a-menu slot="overlay" @click="handleImport">
          <a-menu-item key="mode">导入模版下载</a-menu-item>
          <a-menu-item key="product">导入新产品</a-menu-item>
        </a-menu>
        <a-button v-has="'ArchiveInfoBasicList:import'" style="margin-left: 8px">
          批量导入 <a-icon type="down" />
        </a-button>
      </a-dropdown>
      <a-upload
        style="display: none"
        name="file"
        :showUploadList="false"
        :multiple="false"
        :headers="tokenHeader"
        :action="importExcelUrl"
        @change="handleImportExcel"
        ref="uploadExcel"
      />
      <a-dropdown v-if="selectedRowKeys.length > 0">
        <a-menu slot="overlay">
          <a-menu-item v-has="'ArchiveInfoBasicList:del'" @click="clickDelete()"
            ><a-icon type="delete" />删除产品</a-menu-item
          >
          <a-menu-item v-has="'ArchiveInfoBasicList:delSupplier'" @click="batchDelSupply"
            ><a-icon type="delete" />删除供应商</a-menu-item
          >
        </a-menu>
        <a-button style="margin-left: 8px"> 批量操作 <a-icon type="down" /></a-button>
      </a-dropdown>
    </div>

    <!-- table区域-begin -->
    <div>
      <div class="ant-alert ant-alert-info" style="margin-bottom: 16px">
        <i class="anticon anticon-info-circle ant-alert-icon"></i> 已选择
        <a style="font-weight: 600">{{ selectedRowKeys.length }}</a
        >项
        <a style="margin-left: 24px" @click="onClearSelected">清空</a>
      </div>

      <a-table
        ref="table"
        size="middle"
        bordered
        rowKey="id"
        :scroll="{ x: true }"
        :columns="columns"
        :dataSource="dataSource"
        :pagination="ipagination"
        :loading="loading"
        :rowSelection="{ selectedRowKeys: selectedRowKeys, onChange: onSelectChange }"
        @change="handleTableChange"
      >
        <template #skuTitle>
          SKU编码/产品名称
          <a-tooltip placement="top">
            <template slot="title">
              <span>点击SKU编码可查看产品详情</span>
            </template>
            <a-icon type="info-circle" />
          </a-tooltip>
        </template>
        <template #skuSlot="text, record">
          <div class="sku-box">
            <a-popover v-if="record.hzArchiveInfoImgsList.length" trigger="hover" placement="right">
              <template #content>
                <div class="popover-preview-box">
                  <img :src="record.hzArchiveInfoImgsList[0].url" />
                </div>
              </template>
              <viewer :images="imgsUrlsFormat(record.hzArchiveInfoImgsList)" class="img-box">
                <img
                  :key="item.id"
                  v-show="index == 0"
                  v-for="(item, index) in record.hzArchiveInfoImgsList"
                  :src="item.url"
                />
                <div class="hint-text">{{ record.hzArchiveInfoImgsList.length ? '点击看大图' : '暂无图片' }}</div>
              </viewer>
            </a-popover>

            <div class="text-box">
              <div class="desc-box">
                <div>SKU：</div>
                <div class="name">
                  <span
                    class="sku-code"
                    @click="
                      editId = record.id
                      showDetailModal = true
                    "
                    >{{ record.skuCode }}</span
                  >
                  <a-button type="link" class="copy-btn" icon="copy" @click="copyTo(record.skuCode)"></a-button>
                </div>
              </div>
              <div class="desc-box">
                <div>名称：</div>
                <div class="name">{{ record.nameCn }}[{{ record.nameEn }}]</div>
              </div>
            </div>
          </div>
        </template>
        <template #colorSlot="text, record">
          <div>颜色：{{ record.hzArchiveInfoOtherList[0].color }}</div>
          <div>尺寸：{{ record.hzArchiveInfoOtherList[0].size }}</div>
        </template>
        <template #categoryTitle>
          产品类目
          <a-tooltip placement="top">
            <template slot="title">
              <span>仅显示末级类目名称</span>
            </template>
            <a-icon type="info-circle" />
          </a-tooltip>
        </template>
        <template #specsSlot="text, record">
          <div>
            体积(cm)：{{ record.hzArchiveInfoOtherList[0].len }}*{{ record.hzArchiveInfoOtherList[0].widt }}*{{
              record.hzArchiveInfoOtherList[0].heig
            }}
          </div>
          <div>毛重(KG)：{{ record.hzArchiveInfoOtherList[0].gw }}</div>
          <div>净重(KG)：{{ record.hzArchiveInfoOtherList[0].nw }}</div>
        </template>
        <template #supplierSlot="text, record">
          <template v-if="record.constituteStatus == 1">
            <template v-if="record.hzArchiveInfoSupplierList && record.hzArchiveInfoSupplierList.length">
              <template v-for="item in record.hzArchiveInfoSupplierList">
                <div :key="item.id" v-if="item.izDefault != 0">
                  <div>
                    供应商：<span class="c-blue">{{ item.name }}</span>
                  </div>
                  <div>
                    供应商规格：<span :class="{ 'c-red': item.specsSup > 1 }">{{ item.specsSup }}</span
                    >/组
                  </div>
                  <div>
                    入库规格：<span :class="{ 'c-red': item.specsMy > 1 }">{{ item.specsMy }}</span
                    >/组
                  </div>
                </div>
              </template>
            </template>
            <div v-else class="c-red">未匹配</div>
            <div>采购：{{ record.buyer_dictText }}</div>
          </template>
          <template v-else>-</template>
        </template>
        <template #statusSlot="text, record">
          <!-- 组合状态 -->
          <a-tag v-if="record.constituteStatus == 1" color="#108ee9"> 单品 </a-tag>
          <a-tag v-else color="#87d068"> 组合 </a-tag>
          <!-- 销售状态 -->
          <div class="mt-5">
            <a-tag v-if="record.sellStatus == 2" color="green"> 在售 </a-tag>
            <a-tag v-else-if="record.sellStatus == 1" color="cyan"> 开发中 </a-tag>
            <a-tag v-else-if="record.sellStatus == 3" color="blue"> 清仓 </a-tag>
            <a-tooltip v-else-if="record.sellStatus == 4">
              <template slot="title"> {{ record.haltStatus_dictText }} </template>
              <a-tag color="red"> 停售 </a-tag>
            </a-tooltip>
          </div>
        </template>
        <template #joinManSlot="text, record">
          <div>开发：{{ record.developer_dictText || '无' }}</div>
          <div>设计：{{ record.designer_dictText || '无' }}</div>
          <div>销售：{{ record.saleHead_dictText || '无' }}</div>
        </template>
        <template #timeSlot="text, record">
          <div>创建：{{ record.createTime }} {{ record.createBy }}</div>
          <div>变更：{{ record.updateTime || record.createTime }} {{ record.updateBy || record.createBy }}</div>
        </template>

        <span slot="action" slot-scope="text, record">
          <a
            v-has="'ArchiveInfoBasicList:edit'"
            @click="
              editId = record.id
              isCopy = false
              showEditModal = true
            "
            >编辑</a
          >

          <a-divider type="vertical" />
          <a-dropdown>
            <a class="ant-dropdown-link">更多 <a-icon type="down" /></a>
            <a-menu slot="overlay">
              <a-menu-item v-has="'ArchiveInfoBasicList:add'">
                <a
                  @click="
                    editId = record.id
                    isCopy = true
                    showEditModal = true
                  "
                  >复制产品</a
                >
              </a-menu-item>
              <a-menu-item v-has="'ArchiveInfoBasicList:del'">
                <a @click="clickDelete(record.id)">删除</a>
              </a-menu-item>
              <a-menu-item v-has="'ArchiveInfoBasicList:log'">
                <j-operate-log :id="record.id" />
              </a-menu-item>
            </a-menu>
          </a-dropdown>
        </span>
      </a-table>
    </div>
    <info-basic-modal
      v-if="showEditModal"
      :visible.sync="showEditModal"
      :editId="editId"
      :isCopy="isCopy"
      @submit="modalSubmit"
    />
    <archive-detail-modal
      v-if="showDetailModal"
      :visible.sync="showDetailModal"
      :editId="editId"
      @copy="
        isCopy = true
        showEditModal = true
      "
      @edit="
        isCopy = false
        showEditModal = true
      "
    />
  </a-card>
</template>

<script>
import copyToClipboard from 'copy-to-clipboard'
import { JeecgListMixin } from '@/mixins/JeecgListMixin'
import { deleteAction } from '@/api/manage'

import InfoBasicModal from './modules/InfoBasicModal.vue'
import ArchiveDetailModal from './modules/ArchiveDetailModal.vue'
import ProductCategoryTreeSelect from '@/components/business/ProductCategoryTreeSelect.vue'
import JUrlSelectSearch from '../../components/dict/JUrlSelectSearch.vue'

export default {
  name: 'ArchiveInfoBasicList',
  mixins: [JeecgListMixin],
  components: {
    InfoBasicModal,
    ArchiveDetailModal,
    ProductCategoryTreeSelect,
    JUrlSelectSearch,
  },
  data() {
    return {
      editId: '', //  要编辑或查看的产品档案id，为空表示新增
      isCopy: false, // 是否复制产品档案
      showEditModal: false, // 是否展示编辑弹窗
      showDetailModal: false, // 是否展示详情弹窗
      // 表头
      columns: [
        {
          title: '序号',
          width: 60,
          align: 'center',
          customRender: function (t, r, index) {
            return parseInt(index) + 1
          },
        },
        {
          align: 'center',
          width: 300,
          slots: { title: 'skuTitle' },
          scopedSlots: {
            customRender: 'skuSlot',
          },
        },
        {
          title: '颜色/尺寸',
          align: 'left',
          width: 120,
          scopedSlots: {
            customRender: 'colorSlot',
          },
        },
        {
          align: 'center',
          width: 150,
          dataIndex: 'category_dictText',
          slots: { title: 'categoryTitle' },
          customRender(text, record) {
            return record.category_dictText || '未设置类目'
          },
        },
        {
          title: '单品规格/重量',
          align: 'left',
          scopedSlots: {
            customRender: 'specsSlot',
          },
        },
        {
          title: '采购/供应商',
          align: 'left',
          scopedSlots: {
            customRender: 'supplierSlot',
          },
        },
        {
          title: '申报价值',
          align: 'center',
          customRender(text, record) {
            return record.hzArchiveInfoCustomsList[0].declarePrice.toFixed(2) + ' USD'
          },
        },
        {
          title: '质检类型',
          align: 'center',
          customRender(text, record) {
            if (record.constituteStatus == 2) {
              return '-'
            }
            const item = record.hzArchiveInfoOtherList[0]
            if (item.qualityType == 1) {
              return '免检'
            } else if (item.qualityType == 3) {
              return '全检'
            } else {
              return `抽检（${item.qualityNum}%）`
            }
          },
        },
        {
          title: '状态',
          align: 'center',
          scopedSlots: {
            customRender: 'statusSlot',
          },
        },
        {
          title: '成本中心',
          align: 'center',
          dataIndex: 'deptCode_dictText',
        },
        {
          title: '参与人员',
          align: 'left',
          width: 140,
          scopedSlots: {
            customRender: 'joinManSlot',
          },
        },
        {
          title: '时间',
          align: 'left',
          scopedSlots: {
            customRender: 'timeSlot',
          },
        },
        {
          title: '操作',
          dataIndex: 'action',
          align: 'center',
          fixed: 'right',
          width: 147,
          scopedSlots: { customRender: 'action' },
        },
      ],
      url: {
        list: '/hzkj-product/product/archive/hzArchiveInfoBasic/list',
        delete: '/hzkj-product/product/archive/hzArchiveInfoBasic/delete',
        deleteBatch: '/hzkj-product/product/archive/hzArchiveInfoBasic/deleteBatch',
        exportXlsUrl: '/hzkj-product/product/archive/hzArchiveInfoBasic/exportXls',
        importExcelUrl: 'hzkj-product/product/archive/hzArchiveInfoBasic/importExcel',
        downloadTemplate: '/hzkj-product/product/archive/hzArchiveInfoBasic/exportXlsTemplatesXls',
        deleteSupplyBatch: '/hzkj-product/product/archive/hzArchiveInfoBasic/deleteSupply',
      },
      supplyMatchOptions: [
        { value: '1', text: '全部' },
        { value: '2', text: '未匹配' },
        { value: '3', text: '已匹配' },
        { value: '4', text: '1688未匹配' },
        { value: '5', text: '1688已匹配' },
      ],
      queryParam: {
        nameType: 'cn',
      },
    }
  },
  computed: {
    importExcelUrl: function () {
      return `${window._CONFIG['domianURL']}/${this.url.importExcelUrl}`
    },
    imgsUrlsFormat() {
      return (arr) => (arr || []).map((i) => i.url)
    },
  },
  methods: {
    searchReset() {
      this.queryParam = {
        nameType: 'cn',
      }
      this.loadData(1)
    },
    // 产品名称变化
    updateName() {
      if (this.queryParam.nameType == 'cn') {
        this.queryParam.nameCn = this.queryParam.name
        this.queryParam.nameEn = ''
      } else {
        this.queryParam.nameCn = ''
        this.queryParam.nameEn = this.queryParam.name
      }
    },
    // 复制到剪贴板
    copyTo(value) {
      try {
        copyToClipboard(value)
        this.$message.success(`已复制SKU编码：${value}`)
      } catch (e) {
        this.$message.error('复制失败')
      }
    },
    // 批量导入
    handleImport({ key }) {
      if (key == 'mode') {
        //导入模板下载
        this.handleExportXls('产品档案导入模板', this.url.downloadTemplate)
      } else {
        //导入新产品
        this.$refs.uploadExcel.$el.querySelector('input[type="file"]').click()
      }
    },
    clickDelete(id) {
      this.$confirm({
        content: (h) => {
          return h(
            'div',
            {
              domProps: {
                innerHTML: `<div style="padding-left: 40px;">删除SKU档案后，<span style="color: red">数据不可恢复</span>且已经被采购、仓库、订单<span style="color: red">使用的</span>产品档案<span style="color: red">无法删除</span>，是否继续删除？</div>`,
              },
            },
            []
          )
        },
        onOk: () => {
          // 有id就是删除单个，没id就是批量删除
          const url = id ? this.url.delete : this.url.deleteBatch
          const data = id ? { id: id } : { ids: this.selectedRowKeys.join(',') }
          deleteAction(url, data).then((res) => {
            if (res.success) {
              this.$message.success(res.message)
              setTimeout(() => {
                //重新计算分页问题
                this.reCalculatePage(1)
                this.loadData()
                this.onClearSelected()
              }, 1000)
            } else {
              this.$message.warning(res.message)
            }
          })
        },
      })
    },
    batchDelSupply() {
      this.$confirm({
        content: (h) => {
          return h(
            'div',
            {
              domProps: {
                innerHTML: `<div style="padding-left: 40px;"><span style="font-weight: bold;">将对选中的产品删除对应的供应商信息</span>，<span style="color: red">关系删除后不可恢复</span>，是否继续？</div>`,
              },
            },
            []
          )
        },
        onOk: () => {
          deleteAction(this.url.deleteSupplyBatch, { ids: this.selectedRowKeys.join(',') }).then((res) => {
            if (res.success) {
              this.$message.success(res.message)
            } else {
              this.$message.warning(res.message)
            }
          })
        },
      })
    },
    modalSubmit() {
      // 提交后，因为后端数据存在es缓存，数据更新不及时，延迟后再查
      setTimeout(() => {
        this.modalFormOk()
      }, 1000)
    },
    optionDiy(result) {
      return result.records.map((item) => {
        return {
          ...item,
          value: item.id,
          text: item.name,
        }
      })
    },
  },
}
</script>
<style lang="less" scoped>
@import '~@assets/less/common.less';
.popover-preview-box {
  width: 300px;
  height: 300px;
  position: relative;
  background-color: #fafafa;
  img {
    max-height: 100%;
    max-width: 100%;
    position: absolute;
    left: 50%;
    top: 50%;
    transform: translate(-50%, -50%);
  }
}
.sku-box {
  display: flex;
  text-align: left;
  align-items: center;
  .img-box {
    width: 60px;
    height: 60px;
    margin-right: 10px;
    cursor: pointer;
    position: relative;
    background-color: #fafafa;
    img {
      width: 100%;
      height: 100%;
    }
    .hint-text {
      width: 100%;
      height: 20px;
      line-height: 20px;
      font-size: 11px;
      text-align: center;
      position: absolute;
      left: 0;
      bottom: 0;
      color: #fff;
      background-color: rgba(0, 0, 0, 0.5);
    }
  }
  .text-box {
    max-width: 200px;
  }
  .desc-box {
    display: flex;
    .name {
      word-break: break-all;
      white-space: normal;
    }
  }
  .sku-code {
    cursor: pointer;
    color: #1890ff;
  }
  .copy-btn {
    height: 18px;
    margin-left: 5px;
  }
}
.c-red {
  color: #ff4d4f;
}
.c-blue {
  color: #1890ff;
}
.mt-5 {
  margin-top: 5px;
}
</style>
